import json
from PySide2.QtWidgets import QWidget,QVBoxLayout,QSpacerItem,QSizePolicy
from PySide2.QtCore import Qt,Signal,QMimeData
from PySide2.QtGui import QDragEnterEvent,QDropEvent,QDragMoveEvent
from widget.ui_dataInfoList import Ui_Form

from widget.dataInfoWidget import DataInfoWidget

class DataInfoListWidget(QWidget):

    SigMessage = Signal(str)
    SigFindPosi = Signal(bool)

    def __init__(self, parent: QWidget = None, flags: Qt.WindowFlags = Qt.WindowFlags()) -> None:
        super().__init__(parent, flags)

        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.setAcceptDrops(True)
        self.scroll_area_widget = QWidget(self)
        self.scroll_area_widget.setLayout(QVBoxLayout(self.scroll_area_widget))
        
        self.ui.scrollArea.setWidget(self.scroll_area_widget)
        self.spacer = QSpacerItem(10,10,QSizePolicy.Minimum,QSizePolicy.Expanding)

        self.ui.pushButton_all.clicked.connect(self.but_all_clicked)
        self.ui.pushButton_all_un.clicked.connect(self.but_un_all_clicked)
        self.ui.pushButton_add.clicked.connect(self.but_add_widget_clicked)
        self.ui.pushButton_clear.clicked.connect(self.clear_data_info_widget)

        self.scroll_area_widget.layout().setContentsMargins(1,1,1,1)

    def dragEnterEvent(self, event: QDragEnterEvent) -> None:
        
        if event.mimeData().hasText():
            event.accept()
        else:
            event.ignore()
    
    def dragMoveEvent(self, event: QDragMoveEvent) -> None:
        
        if event.keyboardModifiers() == Qt.CTRL:
            event.setDropAction(Qt.DropAction.CopyAction)
        elif event.keyboardModifiers() == Qt.SHIFT:
            event.setDropAction(Qt.DropAction.MoveAction)        
        else:
            event.setDropAction(Qt.DropAction.CopyAction)

        if self.ui.scrollArea.geometry().contains(event.pos()):
            w = self.childAt(event.pos()).parent()
            if isinstance(w, DataInfoWidget) or self.scroll_area_widget.layout().count() <= 1:
                event.accept()
                index = self.scroll_area_widget.layout().indexOf(w)
                index = 0 if index < 0 else index
                event.mimeData().setProperty('index', index)
                return
        event.ignore()        

    def dropEvent(self, event: QDropEvent) -> None:
        
        try:
            d = json.loads(event.mimeData().text())
            d[DataInfoWidget.X]
            d[DataInfoWidget.Y]
            d[DataInfoWidget.INTERVAL]
            d[DataInfoWidget.EN]
            d[DataInfoWidget.MARKE]
            self.insert_data_info_widget(event.mimeData().property('index'),
                self.init_data_info_widget(d))
            event.accept()
            
        except:
            event.ignore()
    
    def init_data_info_widget(self, data:dict=None) -> DataInfoWidget:

        if data is None:
            w = DataInfoWidget(self)
        else:
            w = DataInfoWidget.from_data_create_widget(data, self)
        w.SigMessage.connect(self.SigMessage)
        w.SigFindPosi.connect(self.SigFindPosi)
        w.SigSendSelf.connect(self.layout_remove_widget)
        return w

    def insert_data_info_widget(self, where:int, w:DataInfoWidget):

        self.scroll_area_widget.layout().insertWidget(where, w)

    def add_data_info_widget(self, w:DataInfoWidget):
        
        self.scroll_area_widget.layout().removeItem(self.spacer)
        self.scroll_area_widget.layout().addWidget(w)
        self.scroll_area_widget.layout().addItem(self.spacer)

    def add_data_info_widgets(self, data_list:list):
        
        self.scroll_area_widget.layout().removeItem(self.spacer)
        for data in data_list:
            self.scroll_area_widget.layout().addWidget(
                self.init_data_info_widget(data)
            )
        self.scroll_area_widget.layout().addItem(self.spacer)
    
    def clear_data_info_widget(self):
        
        count = self.scroll_area_widget.layout().count() - 1
        if count <= 0: return
        count-=1
        while count >= 0:
            w = self.scroll_area_widget.layout().itemAt(count).widget()
            count-=1
            self.layout_remove_widget(w)
    
    def layout_remove_widget(self, w:DataInfoWidget):

        self.scroll_area_widget.layout().removeWidget(w)
        w.close()
        w.deleteLater()

    def but_all_clicked(self):

        count = self.scroll_area_widget.layout().count() - 1
        if count <= 0: return
        for n in range(count):
            dw = self.scroll_area_widget.layout().itemAt(n).widget()
            dw.ui.checkBox_able.setChecked(True)
    
    def but_un_all_clicked(self):

        count = self.scroll_area_widget.layout().count() - 1
        if count <= 0: return
        for n in range(count):
            dw = self.scroll_area_widget.layout().itemAt(n).widget()
            dw.ui.checkBox_able.setChecked(False)

    def data_info_list(self) -> list:

        data_list = []
        count = self.scroll_area_widget.layout().count() - 1
        if count <= 0: return data_list
        for n in range(count):
            dw = self.scroll_area_widget.layout().itemAt(n).widget()
            data_list.append(dw.datainfo())
        return data_list
    
    def but_add_widget_clicked(self):

        w = self.init_data_info_widget()
        self.add_data_info_widget(w)